package com.zz.parkingsystem.controller.admin;

import com.zz.parkingsystem.dto.InsDTO;
import com.zz.parkingsystem.entity.Checkon;
import com.zz.parkingsystem.entity.Inspector;
import com.zz.parkingsystem.service.PCInsService;
import com.zz.parkingsystem.util.OssUtil;
import com.zz.parkingsystem.util.Result;
import com.zz.parkingsystem.util.ResultGenerator;
import com.zz.parkingsystem.vo.AllInsVO;
import com.zz.parkingsystem.vo.BaseInsVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

@RestController
@Api(tags = "展示巡检员信息")
@RequestMapping("admin/ins")
public class AdminInsController {
    @Resource
    private PCInsService pcInsService;

    @ApiOperation(value = "展示巡检员列表",notes = "可以通过巡检员名称，手机号，管理路段进行模糊查询")
    @PostMapping("/getAllIns")
    public Result getAllIns(@RequestBody InsDTO insDto){
        insDto.setStartPage((insDto.getCurrentPage()-1)*insDto.getPageSize());
        List<AllInsVO> list = pcInsService.getAllInsMes(insDto);
        Long total = pcInsService.getCount(insDto);
        Map map = new HashMap();
        map.put("list",list);
        map.put("total",total);
        System.out.println(list);
        return ResultGenerator.genSuccessResult(map);
    }

    @ApiOperation(value = "获取所有的打卡时间段")
    @GetMapping("/check")
    public Result getAllCheck(){
        List<Checkon> checkons = pcInsService.selectCheck();
        if(checkons!=null){
            return ResultGenerator.genSuccessResult(checkons);
        }else{
            return ResultGenerator.genFailResult();
        }

    }

    @ApiOperation(value = "查询单个巡检员信息",notes = "根据id查询单个巡检员信息")
    @GetMapping("{id}")
    public Result getInsOne(@PathVariable("id") Long id){
        Inspector i = pcInsService.selectByPrimaryKey(id);
        return ResultGenerator.genSuccessResult(i);
    }

    @ApiOperation(value = "添加巡检员")
    @PostMapping("")
    public Result addIns(@RequestBody Inspector inspector){
        int i = pcInsService.insertSelective(inspector);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "更改巡检员信息")
    @PutMapping ("")
    public Result updateIns(@RequestBody Inspector inspector){
        int i = pcInsService.updateByPrimaryKeySelective(inspector);
        return ResultGenerator.genSuccessResult();
    }
    @ApiOperation(value = "删除巡检员信息")
    @DeleteMapping("{id}")
    public Result deleteIns(@PathVariable("id") Long id){
        int i = pcInsService.deleteByPrimaryKey(id);
        return ResultGenerator.genSuccessResult(200);
    }

    @ApiOperation(value = "展示巡检员详细信息",notes = "巡检员详情页")
    @GetMapping("sel/{id}")
    public Result getBaseInsMes(@PathVariable("id") Long id){
        BaseInsVO baseIns = pcInsService.getBaseIns(id);
        List<Inspector> orderIns = pcInsService.getOrderIns(id);
        List<Checkon> allCheck = pcInsService.getAllCheck(id);
        List list = new ArrayList();
        list.add(baseIns);
        list.add(orderIns);
        list.add(allCheck);
        return ResultGenerator.genSuccessResult(list);
    }

    @ApiOperation(value = "修改巡检员状态",notes = "禁用")
    @PutMapping("/update/{id}")
    public Result updateJ(@PathVariable("id") Long id){
        int i = pcInsService.updateInsStatusJ(id);
        if(i>0){
            return ResultGenerator.genSuccessResult("修改成功");
        }else{
            return ResultGenerator.genFailResult("修改失败");
        }
    }

    @ApiOperation(value = "修改巡检员状态",notes = "禁用")
    @PutMapping("/update1/{id}")
    public Result updateE(@PathVariable("id") Long id){
        int i = pcInsService.updateInsStatusE(id);
        if(i>0){
            return ResultGenerator.genSuccessResult("修改成功");
        }else{
            return ResultGenerator.genFailResult("修改失败");
        }
    }

    @ApiOperation(value = "下载图片")
    @RequestMapping(value = "/down")
    public ResponseEntity<byte[]> download(HttpServletRequest request,
                                           @RequestParam("filename") String filename,
                                           Model model) throws Exception {
        //下载文件路径
        String path = request.getServletContext().getRealPath("/upload/");
        File file = new File(path + File.separator + filename);
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = new String(filename.getBytes("UTF-8"), "iso-8859-1");
        //通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }

    @Autowired
    private OssUtil ossUtil;//引入工具类

    @ApiOperation(value = "上传图片")
    @PostMapping("/uploadoss")
    public Result fileUpload(@RequestParam("file") MultipartFile file) {
        try {
            String url = ossUtil.uploadFile(file); //调用OSS工具类
            System.out.println(url);
            return ResultGenerator.genSuccessResult(url);
        } catch (Exception e) {
            return  ResultGenerator.genFailResult("上传失败");
        }
    }
}
